<template>
  <BottomDialog :is-show="props.isShow">
    <template #title>
      <p class="text-center text-white font-size-16 font-weight-500 line-height-140 font-style-normal">
        {{ $t('label.forgotPassword') }}
      </p>
    </template>
    <template #prepend-icon>
      <Icon size="16" name="arrowLeft" @click="to(AUTH_ROUTES.LOGIN)"></Icon>
    </template>
    <template #append-icon>
      <slot name="append-icon"></slot>
    </template>
    <template #body>
      <div class="gap-col-24">
        <InputWrap
          v-model="email.value"
          :label="$t('label.email')"
          :placeholder="$t('placeholder.email')"
          :err-msg="email.error"
          :disabled="disabled"
          @focus="email.error = ''"
        ></InputWrap>
        <BlockButton
          :label="$t('common.sendResetPwdLink')"
          :is-gradient="false"
          :disabled="disabled"
          @click="onExecute(validateEmail)"
        ></BlockButton>
      </div>
    </template>
  </BottomDialog>
</template>
<script setup>
import { reactive } from 'vue'
import { useAuthRouteStore } from '@/store/auth-route'
import { $t } from '@/i18n'
import { parseError, useYup } from '@/plugins/yup'
import { AUTH_ROUTES } from '@const'
import BlockButton from '@/components/button/BlockButton.vue'
import BottomDialog from '@/components/dialogs/BottomDialog.vue'
import InputWrap from '@/components/form/InputWrap.vue'
import { useExecutionLock } from '@/compositions/utils'
import { SEND_EMAIL_CODE_TYPE } from '@/constant'
import API from '@/http'

const props = defineProps({
  isShow: {
    type: Boolean,
    default: false,
  },
})

const { to } = useAuthRouteStore()

const email = reactive({
  value: '',
  error: '',
})
const { string } = useYup()
const schema = string().required().email()
const { disabled, onExecute } = useExecutionLock()

async function validateEmail() {
  try {
    await schema.validate(email.value)
    email.error = ''
    await sendResetPwdLink()
  } catch (e) {
    email.error = parseError(e)
  }
}

async function sendResetPwdLink() {
  try {
    const data = {
      email: email.value,
      type: SEND_EMAIL_CODE_TYPE.RESET_PWD,
    }
    await API.Auth.sendEmailCode({ data })
    to(AUTH_ROUTES.RESET_LINK_SENT, { resetPwdEmail: email.value })
  } catch (e) {
    console.error(e)
    throw new Error(e)
  } finally {
    email.value = ''
  }
}
</script>
